package com.example.user.service.code.impl;

import cn.hutool.core.util.ReUtil;
import com.example.framework.common.util.EncryptUtils;
import com.example.module.system.api.sms.SmsSendApi;
import com.example.module.system.dal.redis.RedisKeyConstants;
import com.example.user.config.SmsCodeProperties;
import com.example.user.constants.SourceTypeEnum;
import com.example.user.constants.UserConstants;
import com.example.user.controller.auth.vo.UserSourceType;
import com.example.user.service.code.CodeService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Slf4j
@Service
@RequiredArgsConstructor
public class SmsService extends CodeService {

    @Resource
    private SmsSendApi smsSendApi;

    private final SmsCodeProperties smsCodeProperties;

    @Value("${encrypt.aes.secret}")
    private String aesSecret;

    @Override
    public String getRedisKey(String mobileTel) {
        return RedisKeyConstants.SMS_KEY_PREFIX + EncryptUtils.AesEncrypt(mobileTel, aesSecret);
    }

    @Override
    public void sendCode(UserSourceType reqVo) {
        String mobileTel = reqVo.getId();
        Assert.isTrue(ReUtil.isMatch(UserConstants.MOBILE_PHONE_REGEX, mobileTel), "手机号不合法");
        String identifyingCode = super.checkFrequencyAndGenerateCode(smsCodeProperties.getCodeFrequency(), smsCodeProperties.getLength(), mobileTel, smsCodeProperties.getExpireSeconds());
        String msg = String.format(smsCodeProperties.getTemplate(), identifyingCode);
        log.info("准备发送短信验证码，msg={}", msg);
        smsSendApi.sendSingleMsg(mobileTel, msg);
        super.setCache(smsCodeProperties.getCodeFrequency(), mobileTel, identifyingCode, smsCodeProperties.getExpireSeconds());
    }

    @Override
    public SourceTypeEnum getType() {
        return SourceTypeEnum.SMS;
    }
}
